package cn.k23.interceptor;

import cn.k23.bean.TokenVerifyBean;
import cn.k23.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Description:拦截器类
 * @Author: k23
 * @Date: 2022-05-10 10:07
 * @Version: 1.0
 */
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    TokenUtils tokenUtils;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        boolean result = true; //默认请求可以访问
        String info = null;

        //判断请求头中是否有token的信息
        Object token = request.getHeader("x-token");
        if (null == token){
            //说明用户请求头中没有token 无权访问 直接返回
            info = error("您无权访问");
            result = false;//无权访问
        }else{
            //token验证
            TokenVerifyBean bean = tokenUtils.verifyToken(token.toString());
            if (bean.getCode()!=200){
                info = error(bean.getMsg());
                result = false;
            }
        }
        if (!result){
            //无权访问  响应客户端请求
            response.setContentType("application/json;charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.write(info);
            return result;
        }
        //有权访问，请求继续
        return true;
    }


    String error(String msg){
        StringBuilder sb=new StringBuilder();
        sb.append("{");
       // sb.append("code:0,");
        sb.append("msg:");
        sb.append(msg);
        sb.append("}");
        return sb.toString();
    }

}
